/*!
 * \file test_wt_lmdb_comprehensive.cpp
 * \project WonderTrader
 *
 * \author AI Assistant
 * \date 2024/12/19
 * 
 * \brief LMDB数据库综合测试文件
 * 测试LMDB数据库操作、事务处理等功能
 */

#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include <memory>
#include <string>
#include <vector>
#include <thread>
#include <chrono>
#include <atomic>
#include <map>
#include <filesystem>
#include <fstream>
#include <random>
#include <algorithm>

// LMDB数据库的模拟实现
class MockLMDB {
public:
    struct Transaction {
        bool is_read_only;
        std::map<std::string, std::string> pending_writes;
        bool is_active;
        
        Transaction(bool read_only = false) 
            : is_read_only(read_only), is_active(true) {}
    };
    
    MockLMDB(const std::string& db_path, size_t map_size = 1024 * 1024 * 1024) 
        : db_path_(db_path), map_size_(map_size), is_open_(false) {}
    
    ~MockLMDB() {
        close();
    }
    
    // 打开数据库
    bool open() {
        if (is_open_) return true;
        
        // 创建数据库目录
        std::filesystem::create_directories(db_path_);
        
        // 模拟数据库文件
        std::string db_file = db_path_ + "/data.mdb";
        if (!std::filesystem::exists(db_file)) {
            std::ofstream file(db_file);
            file.close();
        }
        
        is_open_ = true;
        return true;
    }
    
    // 关闭数据库
    void close() {
        if (!is_open_) return;
        
        // 清理所有活跃事务
        std::lock_guard<std::mutex> lock(mutex_);
        transactions_.clear();
        is_open_ = false;
    }
    
    // 开始事务
    std::shared_ptr<Transaction> beginTransaction(bool read_only = false) {
        if (!is_open_) return nullptr;
        
        std::lock_guard<std::mutex> lock(mutex_);
        auto txn = std::make_shared<Transaction>(read_only);
        transactions_.push_back(txn);
        return txn;
    }
    
    // 提交事务
    bool commitTransaction(std::shared_ptr<Transaction> txn) {
        if (!txn || !txn->is_active) return false;
        
        std::lock_guard<std::mutex> lock(mutex_);
        
        // 应用待写入的数据
        for (const auto& pair : txn->pending_writes) {
            data_[pair.first] = pair.second;
        }
        
        txn->is_active = false;
        
        // 从活跃事务列表中移除
        transactions_.erase(
            std::remove(transactions_.begin(), transactions_.end(), txn),
            transactions_.end()
        );
        
        return true;
    }
    
    // 回滚事务
    bool rollbackTransaction(std::shared_ptr<Transaction> txn) {
        if (!txn || !txn->is_active) return false;
        
        std::lock_guard<std::mutex> lock(mutex_);
        
        txn->pending_writes.clear();
        txn->is_active = false;
        
        // 从活跃事务列表中移除
        transactions_.erase(
            std::remove(transactions_.begin(), transactions_.end(), txn),
            transactions_.end()
        );
        
        return true;
    }
    
    // 写入数据
    bool put(std::shared_ptr<Transaction> txn, const std::string& key, const std::string& value) {
        if (!txn || !txn->is_active || txn->is_read_only) return false;
        
        txn->pending_writes[key] = value;
        return true;
    }
    
    // 读取数据
    bool get(std::shared_ptr<Transaction> txn, const std::string& key, std::string& value) {
        if (!txn || !txn->is_active) return false;
        
        std::lock_guard<std::mutex> lock(mutex_);
        
        // 首先检查事务中的待写入数据
        auto pending_it = txn->pending_writes.find(key);
        if (pending_it != txn->pending_writes.end()) {
            value = pending_it->second;
            return true;
        }
        
        // 然后检查已提交的数据
        auto it = data_.find(key);
        if (it != data_.end()) {
            value = it->second;
            return true;
        }
        
        return false;
    }
    
    // 删除数据
    bool del(std::shared_ptr<Transaction> txn, const std::string& key) {
        if (!txn || !txn->is_active || txn->is_read_only) return false;
        
        // 在事务中标记为删除（使用特殊值）
        txn->pending_writes[key] = "__DELETED__";
        return true;
    }
    
    // 检查键是否存在
    bool exists(std::shared_ptr<Transaction> txn, const std::string& key) {
        std::string value;
        return get(txn, key, value) && value != "__DELETED__";
    }
    
    // 获取数据库大小
    size_t size() const {
        std::lock_guard<std::mutex> lock(mutex_);
        return data_.size();
    }
    
    // 获取所有键
    std::vector<std::string> getAllKeys() const {
        std::lock_guard<std::mutex> lock(mutex_);
        std::vector<std::string> keys;
        for (const auto& pair : data_) {
            if (pair.second != "__DELETED__") {
                keys.push_back(pair.first);
            }
        }
        return keys;
    }
    
    // 清空数据库
    void clear() {
        std::lock_guard<std::mutex> lock(mutex_);
        data_.clear();
    }
    
    // 获取数据库统计信息
    struct Stats {
        size_t num_entries;
        size_t total_key_size;
        size_t total_value_size;
        size_t active_transactions;
    };
    
    Stats getStats() const {
        std::lock_guard<std::mutex> lock(mutex_);
        Stats stats = {};
        
        for (const auto& pair : data_) {
            if (pair.second != "__DELETED__") {
                stats.num_entries++;
                stats.total_key_size += pair.first.size();
                stats.total_value_size += pair.second.size();
            }
        }
        
        stats.active_transactions = transactions_.size();
        return stats;
    }
    
    bool isOpen() const { return is_open_; }
    const std::string& getPath() const { return db_path_; }

private:
    std::string db_path_;
    size_t map_size_;
    bool is_open_;
    mutable std::mutex mutex_;
    std::map<std::string, std::string> data_;
    std::vector<std::shared_ptr<Transaction>> transactions_;
};

/**
 * LMDB数据库综合测试类
 * 测试LMDB数据库操作、事务处理等功能
 */
class WtLMDBComprehensiveTest : public ::testing::Test {
protected:
    void SetUp() override {
        // 初始化测试环境
        test_db_path_ = "test_lmdb_" + std::to_string(std::chrono::system_clock::now().time_since_epoch().count());
        db_ = std::make_unique<MockLMDB>(test_db_path_);
        
        // 准备测试数据
        test_data_ = {
            {"key1", "value1"},
            {"key2", "value2"},
            {"key3", "value3"},
            {"user:1001", "张三"},
            {"user:1002", "李四"},
            {"config:timeout", "30"},
            {"config:retries", "3"}
        };
    }

    void TearDown() override {
        // 清理测试环境
        if (db_) {
            db_->close();
        }
        
        // 删除测试数据库目录
        if (std::filesystem::exists(test_db_path_)) {
            std::filesystem::remove_all(test_db_path_);
        }
    }

    std::string test_db_path_;
    std::unique_ptr<MockLMDB> db_;
    std::map<std::string, std::string> test_data_;
};

/**
 * 测试数据库的基本打开和关闭
 */
TEST_F(WtLMDBComprehensiveTest, TestBasicOpenClose) {
    // 测试打开数据库
    EXPECT_FALSE(db_->isOpen());
    bool open_success = db_->open();
    EXPECT_TRUE(open_success);
    EXPECT_TRUE(db_->isOpen());
    
    // 测试重复打开
    bool reopen_success = db_->open();
    EXPECT_TRUE(reopen_success);
    EXPECT_TRUE(db_->isOpen());
    
    // 测试关闭数据库
    db_->close();
    EXPECT_FALSE(db_->isOpen());
    
    // 测试重复关闭
    db_->close();
    EXPECT_FALSE(db_->isOpen());
}

/**
 * 测试基本的事务操作
 */
TEST_F(WtLMDBComprehensiveTest, TestBasicTransactionOperations) {
    ASSERT_TRUE(db_->open());
    
    // 测试开始事务
    auto txn = db_->beginTransaction();
    ASSERT_NE(txn, nullptr);
    EXPECT_TRUE(txn->is_active);
    EXPECT_FALSE(txn->is_read_only);
    
    // 测试提交事务
    bool commit_success = db_->commitTransaction(txn);
    EXPECT_TRUE(commit_success);
    EXPECT_FALSE(txn->is_active);
    
    // 测试回滚事务
    auto txn2 = db_->beginTransaction();
    bool rollback_success = db_->rollbackTransaction(txn2);
    EXPECT_TRUE(rollback_success);
    EXPECT_FALSE(txn2->is_active);
}

/**
 * 测试数据的基本读写操作
 */
TEST_F(WtLMDBComprehensiveTest, TestBasicReadWriteOperations) {
    ASSERT_TRUE(db_->open());
    
    auto txn = db_->beginTransaction();
    ASSERT_NE(txn, nullptr);
    
    // 测试写入数据
    bool put_success = db_->put(txn, "test_key", "test_value");
    EXPECT_TRUE(put_success);
    
    // 测试读取数据（事务内）
    std::string value;
    bool get_success = db_->get(txn, "test_key", value);
    EXPECT_TRUE(get_success);
    EXPECT_EQ(value, "test_value");
    
    // 提交事务
    EXPECT_TRUE(db_->commitTransaction(txn));
    
    // 测试读取数据（新事务）
    auto read_txn = db_->beginTransaction(true);
    bool get_after_commit = db_->get(read_txn, "test_key", value);
    EXPECT_TRUE(get_after_commit);
    EXPECT_EQ(value, "test_value");
    
    db_->commitTransaction(read_txn);
}

/**
 * 测试只读事务
 */
TEST_F(WtLMDBComprehensiveTest, TestReadOnlyTransactions) {
    ASSERT_TRUE(db_->open());
    
    // 先写入一些数据
    auto write_txn = db_->beginTransaction();
    db_->put(write_txn, "readonly_test", "readonly_value");
    db_->commitTransaction(write_txn);
    
    // 测试只读事务
    auto readonly_txn = db_->beginTransaction(true);
    EXPECT_TRUE(readonly_txn->is_read_only);
    
    // 只读事务应该能读取数据
    std::string value;
    bool read_success = db_->get(readonly_txn, "readonly_test", value);
    EXPECT_TRUE(read_success);
    EXPECT_EQ(value, "readonly_value");
    
    // 只读事务不应该能写入数据
    bool write_fail = db_->put(readonly_txn, "new_key", "new_value");
    EXPECT_FALSE(write_fail);
    
    db_->commitTransaction(readonly_txn);
}

/**
 * 测试数据删除操作
 */
TEST_F(WtLMDBComprehensiveTest, TestDataDeletion) {
    ASSERT_TRUE(db_->open());
    
    auto txn = db_->beginTransaction();
    
    // 写入数据
    db_->put(txn, "delete_test", "delete_value");
    EXPECT_TRUE(db_->exists(txn, "delete_test"));
    
    // 删除数据
    bool delete_success = db_->del(txn, "delete_test");
    EXPECT_TRUE(delete_success);
    EXPECT_FALSE(db_->exists(txn, "delete_test"));
    
    db_->commitTransaction(txn);
    
    // 验证删除后的状态
    auto read_txn = db_->beginTransaction(true);
    EXPECT_FALSE(db_->exists(read_txn, "delete_test"));
    db_->commitTransaction(read_txn);
}

/**
 * 测试事务回滚功能
 */
TEST_F(WtLMDBComprehensiveTest, TestTransactionRollback) {
    ASSERT_TRUE(db_->open());
    
    // 先写入一些基础数据
    auto setup_txn = db_->beginTransaction();
    db_->put(setup_txn, "rollback_test", "original_value");
    db_->commitTransaction(setup_txn);
    
    // 开始新事务并修改数据
    auto txn = db_->beginTransaction();
    db_->put(txn, "rollback_test", "modified_value");
    db_->put(txn, "new_key", "new_value");
    
    // 验证事务内的修改
    std::string value;
    EXPECT_TRUE(db_->get(txn, "rollback_test", value));
    EXPECT_EQ(value, "modified_value");
    EXPECT_TRUE(db_->exists(txn, "new_key"));
    
    // 回滚事务
    bool rollback_success = db_->rollbackTransaction(txn);
    EXPECT_TRUE(rollback_success);
    
    // 验证回滚后的状态
    auto verify_txn = db_->beginTransaction(true);
    EXPECT_TRUE(db_->get(verify_txn, "rollback_test", value));
    EXPECT_EQ(value, "original_value"); // 应该恢复到原始值
    EXPECT_FALSE(db_->exists(verify_txn, "new_key")); // 新键不应该存在
    db_->commitTransaction(verify_txn);
}

/**
 * 测试批量数据操作
 */
TEST_F(WtLMDBComprehensiveTest, TestBatchOperations) {
    ASSERT_TRUE(db_->open());
    
    auto txn = db_->beginTransaction();
    
    // 批量写入测试数据
    for (const auto& pair : test_data_) {
        bool success = db_->put(txn, pair.first, pair.second);
        EXPECT_TRUE(success);
    }
    
    // 验证批量写入的数据
    for (const auto& pair : test_data_) {
        std::string value;
        bool success = db_->get(txn, pair.first, value);
        EXPECT_TRUE(success);
        EXPECT_EQ(value, pair.second);
    }
    
    db_->commitTransaction(txn);
    
    // 验证提交后的数据
    auto verify_txn = db_->beginTransaction(true);
    for (const auto& pair : test_data_) {
        std::string value;
        bool success = db_->get(verify_txn, pair.first, value);
        EXPECT_TRUE(success);
        EXPECT_EQ(value, pair.second);
    }
    db_->commitTransaction(verify_txn);
}

/**
 * 测试数据库统计信息
 */
TEST_F(WtLMDBComprehensiveTest, TestDatabaseStatistics) {
    ASSERT_TRUE(db_->open());
    
    // 初始状态
    auto initial_stats = db_->getStats();
    EXPECT_EQ(initial_stats.num_entries, 0);
    EXPECT_EQ(initial_stats.total_key_size, 0);
    EXPECT_EQ(initial_stats.total_value_size, 0);
    
    // 写入数据
    auto txn = db_->beginTransaction();
    for (const auto& pair : test_data_) {
        db_->put(txn, pair.first, pair.second);
    }
    db_->commitTransaction(txn);
    
    // 检查统计信息
    auto stats = db_->getStats();
    EXPECT_EQ(stats.num_entries, test_data_.size());
    EXPECT_GT(stats.total_key_size, 0);
    EXPECT_GT(stats.total_value_size, 0);
    
    // 验证键大小计算
    size_t expected_key_size = 0;
    size_t expected_value_size = 0;
    for (const auto& pair : test_data_) {
        expected_key_size += pair.first.size();
        expected_value_size += pair.second.size();
    }
    
    EXPECT_EQ(stats.total_key_size, expected_key_size);
    EXPECT_EQ(stats.total_value_size, expected_value_size);
}

/**
 * 测试并发事务处理
 */
TEST_F(WtLMDBComprehensiveTest, TestConcurrentTransactions) {
    ASSERT_TRUE(db_->open());
    
    const int num_threads = 4;
    const int operations_per_thread = 25;
    std::atomic<int> success_count(0);
    std::vector<std::thread> threads;
    
    // 多个线程同时进行事务操作
    for (int t = 0; t < num_threads; ++t) {
        threads.emplace_back([this, t, operations_per_thread, &success_count]() {
            for (int i = 0; i < operations_per_thread; ++i) {
                auto txn = db_->beginTransaction();
                if (!txn) continue;
                
                std::string key = "thread_" + std::to_string(t) + "_key_" + std::to_string(i);
                std::string value = "thread_" + std::to_string(t) + "_value_" + std::to_string(i);
                
                if (db_->put(txn, key, value)) {
                    if (db_->commitTransaction(txn)) {
                        success_count.fetch_add(1);
                    }
                } else {
                    db_->rollbackTransaction(txn);
                }
            }
        });
    }
    
    // 等待所有线程完成
    for (auto& thread : threads) {
        thread.join();
    }
    
    // 验证结果
    int expected_operations = num_threads * operations_per_thread;
    EXPECT_EQ(success_count.load(), expected_operations);
    
    // 验证数据完整性
    auto verify_txn = db_->beginTransaction(true);
    for (int t = 0; t < num_threads; ++t) {
        for (int i = 0; i < operations_per_thread; ++i) {
            std::string key = "thread_" + std::to_string(t) + "_key_" + std::to_string(i);
            std::string expected_value = "thread_" + std::to_string(t) + "_value_" + std::to_string(i);
            
            std::string actual_value;
            EXPECT_TRUE(db_->get(verify_txn, key, actual_value));
            EXPECT_EQ(actual_value, expected_value);
        }
    }
    db_->commitTransaction(verify_txn);
}

/**
 * 测试数据库性能特征
 */
TEST_F(WtLMDBComprehensiveTest, TestPerformanceCharacteristics) {
    ASSERT_TRUE(db_->open());
    
    const int num_operations = 1000;
    std::vector<std::pair<std::string, std::string>> perf_data;
    
    // 生成测试数据
    for (int i = 0; i < num_operations; ++i) {
        perf_data.emplace_back(
            "perf_key_" + std::to_string(i),
            "perf_value_" + std::to_string(i) + "_with_some_additional_content"
        );
    }
    
    // 测试写入性能
    auto write_start = std::chrono::high_resolution_clock::now();
    {
        auto txn = db_->beginTransaction();
        for (const auto& pair : perf_data) {
            db_->put(txn, pair.first, pair.second);
        }
        db_->commitTransaction(txn);
    }
    auto write_end = std::chrono::high_resolution_clock::now();
    auto write_duration = std::chrono::duration_cast<std::chrono::microseconds>(write_end - write_start);
    
    // 测试读取性能
    auto read_start = std::chrono::high_resolution_clock::now();
    {
        auto txn = db_->beginTransaction(true);
        for (const auto& pair : perf_data) {
            std::string value;
            db_->get(txn, pair.first, value);
        }
        db_->commitTransaction(txn);
    }
    auto read_end = std::chrono::high_resolution_clock::now();
    auto read_duration = std::chrono::duration_cast<std::chrono::microseconds>(read_end - read_start);
    
    // 输出性能统计
    std::cout << "LMDB性能测试结果:" << std::endl;
    std::cout << "写入 " << num_operations << " 条记录耗时: " << write_duration.count() << " 微秒" << std::endl;
    std::cout << "读取 " << num_operations << " 条记录耗时: " << read_duration.count() << " 微秒" << std::endl;
    std::cout << "平均写入时间: " << static_cast<double>(write_duration.count()) / num_operations << " 微秒/条" << std::endl;
    std::cout << "平均读取时间: " << static_cast<double>(read_duration.count()) / num_operations << " 微秒/条" << std::endl;
    
    // 验证性能合理性
    EXPECT_LT(write_duration.count(), 10000000); // 写入应该在10秒内完成
    EXPECT_LT(read_duration.count(), 5000000);   // 读取应该在5秒内完成
}

/**
 * 测试大数据量处理
 */
TEST_F(WtLMDBComprehensiveTest, TestLargeDataHandling) {
    ASSERT_TRUE(db_->open());
    
    const int large_data_count = 10000;
    std::vector<std::string> keys;
    
    // 生成大量数据
    auto txn = db_->beginTransaction();
    for (int i = 0; i < large_data_count; ++i) {
        std::string key = "large_data_" + std::to_string(i);
        std::string value = "large_value_" + std::to_string(i) + "_" + std::string(100, 'x');
        
        keys.push_back(key);
        bool success = db_->put(txn, key, value);
        EXPECT_TRUE(success);
        
        // 每1000条记录提交一次事务
        if ((i + 1) % 1000 == 0) {
            EXPECT_TRUE(db_->commitTransaction(txn));
            txn = db_->beginTransaction();
        }
    }
    db_->commitTransaction(txn);
    
    // 验证数据完整性
    auto verify_txn = db_->beginTransaction(true);
    int verified_count = 0;
    for (const auto& key : keys) {
        if (db_->exists(verify_txn, key)) {
            verified_count++;
        }
    }
    db_->commitTransaction(verify_txn);
    
    EXPECT_EQ(verified_count, large_data_count);
    
    // 检查数据库统计
    auto stats = db_->getStats();
    EXPECT_GE(stats.num_entries, large_data_count);
    
    std::cout << "大数据量测试: 成功处理 " << large_data_count << " 条记录" << std::endl;
    std::cout << "数据库统计: " << stats.num_entries << " 条记录, "
              << stats.total_key_size << " 字节键, "
              << stats.total_value_size << " 字节值" << std::endl;
}

/**
 * 测试错误处理和恢复
 */
TEST_F(WtLMDBComprehensiveTest, TestErrorHandlingAndRecovery) {
    ASSERT_TRUE(db_->open());
    
    // 测试无效事务操作
    auto invalid_txn = std::shared_ptr<MockLMDB::Transaction>(nullptr);
    EXPECT_FALSE(db_->put(invalid_txn, "key", "value"));
    EXPECT_FALSE(db_->commitTransaction(invalid_txn));
    EXPECT_FALSE(db_->rollbackTransaction(invalid_txn));
    
    // 测试已提交事务的重复操作
    auto txn = db_->beginTransaction();
    db_->put(txn, "test_key", "test_value");
    EXPECT_TRUE(db_->commitTransaction(txn));
    
    // 尝试再次提交已提交的事务
    EXPECT_FALSE(db_->commitTransaction(txn));
    EXPECT_FALSE(db_->rollbackTransaction(txn));
    
    // 测试只读事务的写入尝试
    auto readonly_txn = db_->beginTransaction(true);
    EXPECT_FALSE(db_->put(readonly_txn, "readonly_key", "readonly_value"));
    EXPECT_FALSE(db_->del(readonly_txn, "test_key"));
    db_->commitTransaction(readonly_txn);
    
    // 测试数据库关闭后的操作
    db_->close();
    auto closed_txn = db_->beginTransaction();
    EXPECT_EQ(closed_txn, nullptr);
}

/**
 * 测试数据持久化
 */
TEST_F(WtLMDBComprehensiveTest, TestDataPersistence) {
    // 第一次打开数据库并写入数据
    {
        ASSERT_TRUE(db_->open());
        
        auto txn = db_->beginTransaction();
        for (const auto& pair : test_data_) {
            db_->put(txn, pair.first, pair.second);
        }
        db_->commitTransaction(txn);
        
        db_->close();
    }
    
    // 重新打开数据库并验证数据
    {
        ASSERT_TRUE(db_->open());
        
        auto txn = db_->beginTransaction(true);
        for (const auto& pair : test_data_) {
            std::string value;
            bool success = db_->get(txn, pair.first, value);
            EXPECT_TRUE(success);
            EXPECT_EQ(value, pair.second);
        }
        db_->commitTransaction(txn);
    }
}

/**
 * 测试完整的LMDB工作流程
 */
TEST_F(WtLMDBComprehensiveTest, TestCompleteWorkflow) {
    // 模拟完整的数据库应用场景
    
    // 1. 初始化数据库
    ASSERT_TRUE(db_->open());
    EXPECT_TRUE(db_->isOpen());
    
    // 2. 创建初始数据
    std::map<std::string, std::string> user_data = {
        {"user:1001", "张三,25,工程师"},
        {"user:1002", "李四,30,设计师"},
        {"user:1003", "王五,28,产品经理"}
    };
    
    std::map<std::string, std::string> config_data = {
        {"config:db_timeout", "30"},
        {"config:max_connections", "100"},
        {"config:log_level", "INFO"}
    };
    
    // 3. 批量插入用户数据
    {
        auto txn = db_->beginTransaction();
        for (const auto& pair : user_data) {
            EXPECT_TRUE(db_->put(txn, pair.first, pair.second));
        }
        EXPECT_TRUE(db_->commitTransaction(txn));
    }
    
    // 4. 批量插入配置数据
    {
        auto txn = db_->beginTransaction();
        for (const auto& pair : config_data) {
            EXPECT_TRUE(db_->put(txn, pair.first, pair.second));
        }
        EXPECT_TRUE(db_->commitTransaction(txn));
    }
    
    // 5. 查询和验证数据
    {
        auto txn = db_->beginTransaction(true);
        
        // 验证用户数据
        for (const auto& pair : user_data) {
            std::string value;
            EXPECT_TRUE(db_->get(txn, pair.first, value));
            EXPECT_EQ(value, pair.second);
        }
        
        // 验证配置数据
        for (const auto& pair : config_data) {
            std::string value;
            EXPECT_TRUE(db_->get(txn, pair.first, value));
            EXPECT_EQ(value, pair.second);
        }
        
        EXPECT_TRUE(db_->commitTransaction(txn));
    }
    
    // 6. 更新部分数据
    {
        auto txn = db_->beginTransaction();
        EXPECT_TRUE(db_->put(txn, "user:1001", "张三,26,高级工程师")); // 升职加薪
        EXPECT_TRUE(db_->put(txn, "config:max_connections", "200"));   // 扩容
        EXPECT_TRUE(db_->commitTransaction(txn));
    }
    
    // 7. 验证更新结果
    {
        auto txn = db_->beginTransaction(true);
        
        std::string user_info;
        EXPECT_TRUE(db_->get(txn, "user:1001", user_info));
        EXPECT_EQ(user_info, "张三,26,高级工程师");
        
        std::string max_conn;
        EXPECT_TRUE(db_->get(txn, "config:max_connections", max_conn));
        EXPECT_EQ(max_conn, "200");
        
        EXPECT_TRUE(db_->commitTransaction(txn));
    }
    
    // 8. 删除部分数据
    {
        auto txn = db_->beginTransaction();
        EXPECT_TRUE(db_->del(txn, "user:1003")); // 王五离职
        EXPECT_TRUE(db_->commitTransaction(txn));
    }
    
    // 9. 验证删除结果
    {
        auto txn = db_->beginTransaction(true);
        EXPECT_FALSE(db_->exists(txn, "user:1003"));
        EXPECT_TRUE(db_->exists(txn, "user:1001"));
        EXPECT_TRUE(db_->exists(txn, "user:1002"));
        EXPECT_TRUE(db_->commitTransaction(txn));
    }
    
    // 10. 生成最终报告
    auto final_stats = db_->getStats();
    std::cout << "LMDB工作流程完成:" << std::endl;
    std::cout << "- 最终记录数: " << final_stats.num_entries << std::endl;
    std::cout << "- 总键大小: " << final_stats.total_key_size << " 字节" << std::endl;
    std::cout << "- 总值大小: " << final_stats.total_value_size << " 字节" << std::endl;
    std::cout << "- 活跃事务数: " << final_stats.active_transactions << std::endl;
    
    // 验证最终状态
    EXPECT_EQ(final_stats.num_entries, user_data.size() - 1 + config_data.size()); // 删除了一个用户
    EXPECT_EQ(final_stats.active_transactions, 0);
    
    // 11. 清理和关闭
    db_->close();
    EXPECT_FALSE(db_->isOpen());
} 